<template>
	<view class="layout" :class="{ noSkelett: !isSkelett }">
		<view class="layout-header">
			<DistributionNavBar rgb="#fff">
				<view slot="center" class="layout-header-center">
					<DistributionSearch :swiperList="materialSearchHistory" source="material" />
				</view>
			</DistributionNavBar>
		</view>

		<!-- 轮播图 -->
		<view v-if="isBannerListLength" class="layout-banner">
			<DistributionCarousel :list="bannerList" itemPadding="0 20rpx" type="material" :height="320" />
		</view>

		<!-- 作品精选 -->
		<DistributionMaterialFeatured
			:total="total"
			:isFlag="isFlag"
			:list="featuredWorks"
			:circular="isCircular"
			:autoPlay="swiperAutoPlay"
			@callBack="changeCallBack"
			@playCallBack="clickPlayCallBack"
		/>

		<!-- 页签 & 排序 -->
		<view class="layout-searchSort" :class="{ fixed: isFixed }">
			<DistributionTabs
				bgColor
				type="material"
				:skelettSize="5"
				:isActiveIcon="false"
				:current="tabCurrent"
				:list="productTypeList"
				ref="DistributionTabs"
				:isSkelett="isSkelett"
				@change="tabChange"
				@changeFixedCallBack="changeFixedCallBack"
			>
				<template slot="left">
					<view @click="openCitySite" class="layout-searchSort-left" v-show="currentSite.city">
						<text>{{ currentSite.city }}</text>
						<image :src="siteIcon" />
					</view>
				</template>
			</DistributionTabs>
		</view>

		<view class="layout-main">
			<DistributionMaterial :isSkelett="isSkelett" :list="materialList" />
		</view>

		<DistributionHint :type="isHintStatus" />

		<!-- 素材圈规则说明 -->
		<DistributionMaterialRule />

		<DistributionTabBar :tabIndex="2" />
	</view>
</template>

<script>
import { debounce } from 'lodash';
import { defaultImageUrl } from '@/utils';
import { mapGetters, mapMutations } from 'vuex';
import { formatCommissionsModel } from '@/utils/common';
import { getProductList, getIndexListBanner, getMaterialFeaturedWorks } from '@/api';

import DistributionTabs from '@/components/distributionTabs';
import DistributionHint from '@/components/distributionHint';
import DistributionTabBar from '@/components/distributionTabBar';
import DistributionSearch from '@/components/distributionSearch';
import DistributionMaterial from '@/components/distributionMaterial';
import DistributionCarousel from '@/components/distributionCarousel';
import DistributionNavBar from '@/components/distributionNavBar/indeHome';
import DistributionMaterialRule from '@/components/distributionMaterialRule';
import DistributionMaterialFeatured from '@/components/distributionMaterialFeatured';

const siteIcon = Object.freeze(`${defaultImageUrl}icon/icon_register_down.png`);

const productTypeList = Object.freeze([
	{
		type: 0,
		label: '综合排序'
	},
	{
		type: 4,
		label: '最新'
	},
	{
		type: 5,
		code: 'allImgCount',
		fixedReminder: '图片'
	},
	{
		type: 6,
		code: 'allVideoCount',
		fixedReminder: '视频'
	}
]);

export default {
	data() {
		this.debounced = debounce((e) => {
			!this.isSkelett && this.$refs?.DistributionTabs.changePageScroll?.(e);
		}, 5);

		return {
			siteIcon,
			productTypeList,

			tabCurrent: 0,
			isSkelett: true,

			bannerList: [],
			materialList: [],

			total: 0,
			isFlag: false,
			isLoading: false,
			isCircular: false,
			swiperAutoPlay: true,
			featuredRequestParams: {
				pageIndex: 1,
				pageSize: 10
			},

			isFixed: false,
			isPageScrollTo: false,
			isHintStatus: '', // nomore  nodata
			requestParams: {
				productType: 2,
				pageIndex: 1,
				pageSize: 10
			}
		};
	},

	computed: {
		...mapGetters(['coordinate', 'currentSite', 'materialSearchHistory']),

		isBannerListLength() {
			const { bannerList } = this;

			return !!bannerList.length;
		},

		featuredWorks() {
			const { list = [] } = this.$store.state.temporary.featuredWorks;

			return list;
		}
	},

	watch: {
		currentSite: {
			immediate: true,
			handler(afterParams, beforeParams) {
				this.isPageScrollTo = true;

				this.changeFeaturedWorks({
					total: 0,
					list: []
				});

				this.getBannerList(afterParams.id);
				this.getMaterialResourceList(1);
				this.getFeaturedWorks(1, true);
			}
		}
	},

	methods: {
		...mapMutations(['changeFeaturedWorks']),

		getBannerList(locationId) {
			getIndexListBanner({
				locationId,
				position: 2 //  1 首页 2 素材圈
			}).then((res) => {
				const { code, data } = res;

				if (code !== 200) {
					return;
				}

				this.bannerList = data || [];
				this.$nextTick((e) => {
					this.$refs?.DistributionTabs?.init();
				});
			});
		},

		getMaterialResourceList(pageIndex = this.requestParams.pageIndex) {
			const {
				coordinate,
				tabCurrent,
				currentSite: { id },
				requestParams: { pageSize, productType }
			} = this;

			const sortStr = this.productTypeList[tabCurrent]?.type || productTypeList[tabCurrent]?.type;

			const params = {
				...coordinate,

				pageSize,
				sortStr,
				pageIndex,
				productType,
				locationIdStr: id
			};

			const isPageIndex = pageIndex === 1;

			getProductList(params).then((res) => {
				const { code, data } = res;

				if (code !== 200) {
					return;
				}

				const { list } = data;

				const filterList = (list?.data || []).map((item) => {
					let { endTime, distance, commissionsList, ...otherParams } = item;
					let filtersDistance = distance;

					if (distance) {
						filtersDistance = distance < 1000 ? `${distance}m` : `${(distance / 1000).toFixed(2)}km`;
					}

					return Object.assign({
						...otherParams,
						distance: filtersDistance,
						commissionsList: formatCommissionsModel(commissionsList)
					});
				});

				const len = filterList.length;

				this.requestParams.pageIndex = pageIndex;
				this.materialList = isPageIndex ? [...filterList] : [...this.materialList, ...filterList];

				this.isHintStatus = isPageIndex && !len ? 'nodata' : len < pageSize ? 'nomore' : '';

				isPageIndex &&
					(this.productTypeList = this.productTypeList.map((item) =>
						!item.code
							? item
							: {
									...item,
									label: `${item.fixedReminder}(${data?.[item.code] || 0})`
							  }
					));

				this.$nextTick((e) => {
					this.isSkelett = false;
				});
			});
		},

		openCitySite() {
			const url = `/otherPage/CitySite`;

			uni.navigateTo({
				url
			});
		},

		tabChange(current) {
			const isCurrent = this.tabCurrent === current;

			if (isCurrent) {
				return;
			}

			const { fixedTop, isTabsFixed } = this.$refs.DistributionTabs;

			isTabsFixed &&
				uni.pageScrollTo({
					scrollTop: fixedTop,
					duration: 10
				});

			this.tabCurrent = current;
			this.getMaterialResourceList(1);
		},

		async getFeaturedWorks(pageIndex = this.featuredRequestParams.pageIndex, status) {
			const {
				currentSite: { id },
				featuredRequestParams: { pageSize }
			} = this;

			const params = {
				pageSize,
				pageIndex,
				locationId: id
			};

			const { code, data } = await getMaterialFeaturedWorks(params);

			if (code !== 200) {
				return;
			}

			const isPageIndex = pageIndex === 1;
			const { displayFlag, list, total } = data || {};
			console.log('🚀 ~ file: Material.vue ~ line 306 ~ getFeaturedWorks ~ list', list);

			this.total = total;

			this.isLoading = false;

			this.isFlag = displayFlag;
			this.featuredRequestParams.pageIndex = pageIndex;

			const formatList = isPageIndex ? list || [] : [...this.featuredWorks, ...(list || [])];

			this.changeFeaturedWorks({
				total,
				list: formatList
			});
			this.isCircular = formatList.length === total;

			status &&
				this.$nextTick((e) => {
					this.$refs?.DistributionTabs?.init();
				});
		},

		changeCallBack(index) {
			const {
				total,
				isLoading,
				featuredWorks,
				featuredRequestParams: { pageIndex }
			} = this;

			this.isCircular = true;

			if (total === featuredWorks.length) {
				return;
			}

			if (index === 1) {
				this.isCircular = false;
			}

			const diff = featuredWorks.length - index;

			if (diff > 5 || isLoading) {
				return;
			}

			this.isLoading = true;
			this.getFeaturedWorks(pageIndex + 1);
		},

		clickPlayCallBack(status = true) {
			this.swiperAutoPlay = status;
		},

		changeFixedCallBack(status) {
			this.isFixed = status;
		}
	},

	onShow() {
		const { isPageScrollTo } = this;
		this.clickPlayCallBack();

		isPageScrollTo &&
			this.$nextTick((e) => {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0,
					success: () => {
						this.isPageScrollTo = false;

						setTimeout((e) => {
							this.$refs?.DistributionTabs.init?.(e);
						}, 100);
					}
				});
			});
	},

	onReachBottom() {
		const {
			isSkelett,
			isHintStatus,
			requestParams: { pageIndex }
		} = this;

		if (isHintStatus || isSkelett) {
			return;
		}

		this.isHintStatus = 'loading';
		this.getMaterialResourceList(pageIndex + 1);
	},

	onPageScroll(e) {
		this.debounced(e);
	},

	components: {
		DistributionTabs,
		DistributionHint,
		DistributionSearch,
		DistributionNavBar,
		DistributionTabBar,
		DistributionCarousel,
		DistributionMaterial,
		DistributionMaterialRule,
		DistributionMaterialFeatured
	}
};
</script>

<style lang="scss" scoped>
@import '@/style/common.scss';

.layout {
	background: #f6f6f6;
	@include Db_iosBottomDistance(120rpx);

	&-header {
		&-center {
			flex: 1;
			height: 64rpx;
		}
	}

	&-banner {
		height: 320rpx;
		margin-top: 20rpx;
	}

	// 页签 & 排序
	&-searchSort {
		height: 200rpx;
		overflow: hidden;
		background-repeat: no-repeat;
		background-size: 100% 100%;

		padding-top: 8rpx;

		&-left {
			color: #333;
			font-size: 28rpx;
			font-weight: 500;
			height: 56rpx;

			display: flex;
			align-items: center;
			padding-left: 20rpx;

			text {
				display: inline-block;
				max-width: 120rpx;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}

			image {
				width: 40rpx;
				height: 40rpx;
				margin-left: 8rpx;
			}
		}

		&.fixed {
			/deep/ .e-tab-item {
				background: #f6f6f6;
			}
		}
	}

	&-main {
		margin-top: -100rpx;
		padding: 0 20rpx;
	}

	&.noSkelett {
		/deep/ .e-tab-item {
			&.active {
				color: #fff;
				background: #ff6b11 !important;
			}

			text {
				min-width: 60rpx;
			}
		}
	}

	/deep/ .distributionCarousel-footer-defaultIndicator {
		right: 40rpx;
		bottom: 16rpx;
	}
}
</style>
